import { NextRequest, NextResponse } from 'next/server'
import OpenAI from 'openai'

// OpenAI配置
const OPENAI_API_KEY = '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'

// 创建OpenAI客户端实例
const openai = new OpenAI({
  apiKey: OPENAI_API_KEY,
})

// 主题映射
const themeMapping = {
  friendship: '友谊与分享',
  courage: '勇气与冒险',
  kindness: '善良与爱心',
  learning: '学习与成长',
  nature: '自然与环保',
  family: '家庭与亲情',
}

// 年龄组映射
const ageGroupMapping = {
  '3-5': '适合3-5岁儿童',
  '6-8': '适合6-8岁儿童',
  '9-12': '适合9-12岁儿童',
}

/**
 * 使用OpenAI DALL-E生成插图
 * @param prompt 图片生成提示词
 * @returns 生成的图片URL或null
 */
async function generateOpenAIIllustration(prompt: string): Promise<string | null> {
  try {
    console.log('开始使用OpenAI DALL-E生成插图...')
    console.log('提示词:', prompt)

    const response = await openai.images.generate({
      model: 'dall-e-3', // 使用DALL-E 3模型，质量更高
      prompt: prompt,
      n: 1, // 生成1张图片
      size: '1024x1024', // 1024x1024像素
      quality: 'standard', // 标准质量
      style: 'vivid', // 生动风格，适合儿童绘本
    })

    console.log('OpenAI API响应:', response)

    if (response.data && response.data[0] && response.data[0].url) {
      const imageUrl = response.data[0].url
      console.log('成功生成插图，URL:', imageUrl)
      return imageUrl
    } else {
      console.error('API响应中没有图片URL:', response)
      return null
    }
  } catch (error: any) {
    console.error('OpenAI插图生成失败:', error)
    
    if (error.response) {
      console.error('错误响应:', error.response.data)
    }
    
    return null
  }
}

/**
 * 生成适合儿童绘本的插图提示词
 * @param theme 故事主题
 * @param ageGroup 目标年龄组
 * @param storyContent 故事内容摘要
 * @param illustrationType 插图类型
 * @returns 优化的提示词
 */
function generateIllustrationPrompt(
  theme: string,
  ageGroup: string,
  storyContent: string,
  illustrationType: 'main' | 'comic' = 'main'
): string {
  const themeName = themeMapping[theme as keyof typeof themeMapping] || theme
  const ageDescription = ageGroupMapping[ageGroup as keyof typeof ageGroupMapping] || ageGroup
  
  // 根据插图类型生成不同的提示词
  if (illustrationType === 'main') {
    // 主插图：水彩风格，温暖明亮
    return `Create a beautiful watercolor illustration for a children's picture book. 
    Theme: ${themeName} (${theme})
    Target age: ${ageDescription}
    Style: Soft watercolor painting with warm, bright colors
    Content: ${storyContent.substring(0, 200)}...
    Requirements:
    - Whimsical and child-friendly art style
    - Soft, dreamy watercolor technique
    - Warm and inviting color palette
    - Cute, expressive characters
    - Safe and positive imagery
    - High quality, professional children's book illustration
    - No text or words in the image
    - Suitable for ${ageGroup} year old children`
  } else {
    // 漫画插图：卡通风格，生动有趣
    return `Create a vibrant cartoon illustration for a children's comic panel. 
    Theme: ${themeName} (${theme})
    Target age: ${ageDescription}
    Style: Colorful cartoon with bold, clean lines
    Content: ${storyContent.substring(0, 150)}...
    Requirements:
    - Bright, energetic cartoon style
    - Bold, clean line work
    - Vibrant, saturated colors
    - Expressive, cute characters
    - Dynamic composition
    - Child-safe content
    - Comic panel format
    - No text or speech bubbles
    - Suitable for ${ageGroup} year old children`
  }
}

/**
 * 生成备用插图（当OpenAI API失败时使用）
 * @param theme 故事主题
 * @param ageGroup 目标年龄组
 * @returns 占位符图片URL
 */
function generateFallbackIllustration(theme: string, ageGroup: string): string {
  const colors = {
    friendship: '#FFB6C1', // 粉色
    courage: '#87CEEB',    // 天蓝色
    kindness: '#98FB98',   // 浅绿色
    learning: '#DDA0DD',   // 梅红色
    nature: '#90EE90',     // 浅绿色
    family: '#F0E68C',     // 卡其色
  }
  
  const color = colors[theme as keyof typeof colors] || '#87CEEB'
  const colorHex = color.replace('#', '')
  
  return `https://via.placeholder.com/1024x1024/${colorHex}/FFFFFF?text=AI+Generated+Illustration`
}

export async function POST(request: NextRequest) {
  try {
    const { 
      theme, 
      ageGroup, 
      storyContent, 
      illustrationType = 'main',
      useOpenAI = true 
    } = await request.json()

    // 验证必要参数
    if (!theme || !ageGroup || !storyContent) {
      return NextResponse.json({ 
        error: '缺少必要参数：theme, ageGroup, storyContent' 
      }, { status: 400 })
    }

    // 检查OpenAI API密钥
    if (!OPENAI_API_KEY || OPENAI_API_KEY === 'your-openai-api-key-here') {
      console.warn('OpenAI API密钥未配置，使用备用插图')
      const fallbackUrl = generateFallbackIllustration(theme, ageGroup)
      return NextResponse.json({ 
        imageUrl: fallbackUrl,
        source: 'fallback',
        message: 'OpenAI API密钥未配置，使用备用插图'
      })
    }

    // 生成插图提示词
    const prompt = generateIllustrationPrompt(theme, ageGroup, storyContent, illustrationType)
    console.log('生成的提示词:', prompt)

    let imageUrl: string | null = null
    let source = 'fallback'

    // 尝试使用OpenAI生成插图
    if (useOpenAI) {
      imageUrl = await generateOpenAIIllustration(prompt)
      if (imageUrl) {
        source = 'openai'
      }
    }

    // 如果OpenAI失败，使用备用插图
    if (!imageUrl) {
      console.log('OpenAI生成失败，使用备用插图')
      imageUrl = generateFallbackIllustration(theme, ageGroup)
    }

    return NextResponse.json({
      imageUrl,
      source,
      prompt,
      theme,
      ageGroup,
      illustrationType,
      timestamp: new Date().toISOString()
    })

  } catch (error) {
    console.error('生成插图时出错:', error)
    return NextResponse.json({ 
      error: '生成插图失败，请稍后重试',
      details: error instanceof Error ? error.message : '未知错误'
    }, { status: 500 })
  }
} 